<template>
  <a-card :bordered="false" class="card-area">
    <div :class="advanced ? 'search' : null">
      <!-- 搜索区域 -->
      <a-form layout="horizontal">
        <div :class="advanced ? null: 'fold'">
          <a-row >
            <a-col :md="12" :sm="24">
              <a-form-item label="行业类别编码"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <pagination-search-select v-model="queryParams.industryType" :listUrl="listUrl[0]" :listUrlParam="listUrlParam"
                                          valueName="industryType" :showNameArr="['industryType','industryName']"
                                          :pageSize="10" :openSearch="true" :searchWordKeyArr="industryTypeSearchKey">
                </pagination-search-select>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-form-item label="通道标识"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  v-model="queryParams.destChannel">
                  <a-select-option key="WXZF">微信</a-select-option>
                  <a-select-option key="ALIP">支付宝</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :md="12" :sm="24">
              <a-form-item label="经营类目编码"
                           :labelCol="{span: 5}"
                           :wrapperCol="{span: 18, offset: 1}">
                <a-select
                  mode="default"
                  :allowClear="true"
                  style="width: 100%"
                  show-search
                  placeholder="请选择"
                  option-filter-prop="children"
                  :filter-option="filterOption"
                  @focus="selectDestCatalogCd"
                  @search="selectDestCatalogCd"
                  v-model="queryParams.destCatalogCd">
                  <a-select-option v-for="(d,index) in destCatalogCdData" :key="d.ID">
                    {{ d.ID }}-{{ d.NAME}}
                  </a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>


        </div>
        <div style="text-align: center" >
          <a-button type="primary" @click="search">查询</a-button>
          <a-button style="margin-left: 8px" @click="reset">重置</a-button>
        </div>
      </a-form>
    </div>

    <div>
      <div class="operator">
        <a-button v-hasPermission="['industryMap:add']" ghost type="primary" @click="addIndustryMap">新增</a-button>
      </div>
      <!-- 表格区域 -->
      <a-table ref="TableInfo"
               :columns="columns"
               :rowKey="record => record.id"
               :dataSource="dataSource"
               :pagination="pagination"
               :loading="loading"
               :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
               :scroll="{ x: 1186 }"
               @change="handleTableChange">
        <template slot="email" slot-scope="text, record">
          <a-popover placement="topLeft">
            <template slot="content">
              <div>{{text}}</div>
            </template>
            <p style="width: 150px;margin-bottom: 0">{{text}}</p>
          </a-popover>
        </template>
        <template slot="industryMapOperation" slot-scope="text, record">
          <a-icon v-hasPermission="['industryMap:edit']" type="setting" theme="twoTone" twoToneColor="#4a9ff5"
                  @click="editIndustryMap(record)" title="修改"></a-icon>&nbsp;
          <a-icon v-hasPermission="['industryMap:cancel']" type="poweroff" twoToneColor="#4a9ff5"
                  @click="cancelIndustryMap(record)" title="注销"></a-icon>&nbsp;
          <a-icon v-hasPermission="['industryMap:view']" type="eye" theme="twoTone" twoToneColor="#42b983"
                  @click="viewIndustryMap(record)" title="查看"></a-icon>
          <a-badge v-hasNoPermission="['industryMap:edit','industryMap:cancel','industryMap:view']"
                   userStatus="warning" text="无权限"></a-badge>
        </template>

      </a-table>

      <!-- 操作 -->
      <industry-map-operation
        ref="industryMapOperation"
        @close="handleIndustryMapOperationClose"
        @success="handleIndustryMapOperationSuccess"
        :industryMapOperationVisiable="industryMapOperation.visiable">
      </industry-map-operation>

    </div>
  </a-card>
</template>

<script>
  import RangeDate from '@/components/datetime/RangeDate';
  import {mapState} from "vuex"
  import IndustryMapOperation from "./IndustryMapOperation";
  import PaginationSearchSelect from '@/components/select/PaginationSearchSelect'

  export default {
    name: "IndustryMap",
    components: {IndustryMapOperation, RangeDate,PaginationSearchSelect},
    data() {
      return {
        listUrl: ['/admin/mcmp/bMchntBaseInfo/indusSelect2List', '/admin/merParam/industryMapInfo/destCatalogCdSelect2List'],
        listUrlParam: {'q': ''},
        industryTypeSearchKey:['industryType'],
        advanced: false,
        industryMapOperation: {
          visiable: false,
        },

        industryTypeData: [],
        destCatalogCdData: [],
        queryParams: {
          industryType: '',
          destChannel: '',
          destCatalogCd: '',
        },

        dataSource: [],
        sortedInfo: null,
        paginationInfo: null,
        selectedRowKeys: [],
        pagination: {
          pageSizeOptions: ['10', '20', '30', '40', '100'],
          defaultCurrent: 1,
          defaultPageSize: 10,
          showQuickJumper: true,
          showSizeChanger: true,
          showTotal: (total, range) => `显示 ${range[0]} ~ ${range[1]} 条记录，共 ${total} 条记录`
        },
        loading: false,

      }
    },
    computed: {
      ...mapState({
        user: state => state.account.user,
      }),
      columns() {
        let {sortedInfo} = this
        sortedInfo = sortedInfo || {}
        let {filteredInfo} = this
        filteredInfo = filteredInfo || {}
        return [{
          title: '行业类别编码',
          dataIndex: 'industryType',
          scopedSlots: {customRender: 'industryType'},
        }, {
          title: '行业类别名称',
          dataIndex: 'industryName',
          scopedSlots: {customRender: 'industryName'},
        }, {
          title: '通道标识',
          dataIndex: 'destChannel',
          customRender: (text, row, index) => {
            switch (text) {
              case 'ALIP':
                return '支付宝'
              case 'WXZF':
                return '微信'
              default:
                return text
            }
          }
        }, {
          title: '经营类目编码',
          dataIndex: 'destCatalogCd',
          scopedSlots: {customRender: 'destCatalogCd'},
        }, {
          title: '经营类目名称',
          dataIndex: 'destCatalogName',
          scopedSlots: {customRender: 'destCatalogName'},
        }, {
          title: '状态',
          dataIndex: 'status',
          customRender: (text, row, index) => {
            switch (text) {
              case '00':
                return '非正式'
              case '01':
                return '正式'
              case '02':
                return '停用'
              case '03':
                return '已注销'
              default:
                return text
            }
          },
        }, {
          title: '操作',
          dataIndex: 'industryMapOperation',
          fixed: 'right',
          width: 100,
          show: false,
          scopedSlots: {customRender: 'industryMapOperation'}
        }]
      }
    },
    mounted() {
      this.fetch()
    },
    //下拉框分页名称分页
   /* watch: {
        'query.instId'(newValue, oldValue) {
            if (newValue !== oldValue) {
                this.listUrlParam= {'instId': newValue}

                this.$refs.industryTypeSelect.listUrlParam= {'instId': newValue}
                this.$refs.industryTypeSelect.loadDatas();
            }
        }
    },*/
    methods: {
      filterOption(input, option) {
        return (
          option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
        );
      },

      selectIndustryType(val) {

        this.industryTypeData = []

        let param = {}
        if (val) {
          param = {
            q: encodeURIComponent(val),
            pageSize: 20
          }
        } else {
          param = {
            q: '',
            pageSize: 20
          }
        }
        this.$get('admin/mcmp/bMchntBaseInfo/indusSelect2List', param).then((r) => {
          let result = r.data.rows
          result.forEach(r => {
            this.industryTypeData.push(r);
          })
        })
      },

      selectDestCatalogCd(val) {
        this.destCatalogCdData = []

        let destChannel = this.queryParams.destChannel
        if (destChannel) {
          let param = {}
          if (val) {
            param = {
              q: encodeURIComponent(destChannel + `&${val}`),
              pageSize: 20
            }
          } else {
            param = {
              q: encodeURIComponent(destChannel),
              pageSize: 20
            }
          }
          this.$get('admin/merParam/industryMapInfo/destCatalogCdSelect2List', param).then((r) => {
            let result = r.data.rows
            result.forEach(r => {
              this.destCatalogCdData.push(r);
            })
          })
        } else {
          this.$message.warning('请先选择通道标识!')
          return;
        }
      },

      onSelectChange(selectedRowKeys) {
        this.selectedRowKeys = selectedRowKeys
      },

      handleIndustryMapOperationClose() {
        this.industryMapOperation.visiable = false
      },
      handleIndustryMapOperationSuccess() {
        this.industryMapOperation.visiable = false
        this.$message.success('操作成功')
        this.search()
      },


      addIndustryMap() {
        this.industryMapOperation.visiable = true
      },
      viewIndustryMap(record) {
        record.operation = 'view'
        this.$refs.industryMapOperation.setIndustryMapFormValues(record)
        this.industryMapOperation.visiable = true
      },
      editIndustryMap(record) {
        record.operation = 'edit'

        if (record.status == "03" ) {
          this.$message.warning("已注销数据不允许修改");
        } else {
          this.$refs.industryMapOperation.setIndustryMapFormValues(record)
          this.industryMapOperation.visiable = true
        }
      },
      cancelIndustryMap(record) {
        record.operation = 'cancel'
        if (record.status == "03" ) {
          this.$message.warning("已注销数据不允许重复注销");
        } else {
          this.$refs.industryMapOperation.setIndustryMapFormValues(record)
          this.industryMapOperation.visiable = true
        }
      },

      search() {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        let {sortedInfo, filteredInfo} = this
        let sortField, sortOrder
        // 获取当前列的排序和列的过滤规则
        if (sortedInfo) {
          sortField = sortedInfo.field
          sortOrder = sortedInfo.order
        }
        let params = this.queryParams

        this.fetch({
          sortField: sortField,
          sortOrder: sortOrder,
          ...params,
          ...filteredInfo
        })
      },
      reset() {
        // 取消选中
        this.selectedRowKeys = []
        // 重置分页
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }
        // 重置列排序规则
        this.sortedInfo = null
        // 重置查询参数
        this.queryParams = {}
        // // 清空时间选择
        // this.$refs.createTime.reset()
        this.fetch()
      },
      handleTableChange(pagination, filters, sorter) {
        this.$refs.TableInfo.pagination.current = this.pagination.defaultCurrent
        if (this.paginationInfo) {
          this.paginationInfo.current = this.pagination.defaultCurrent
          this.paginationInfo.pageSize = this.pagination.defaultPageSize
        }

        // 将这三个参数赋值给Vue data，用于后续使用
        this.paginationInfo = pagination
        this.filteredInfo = filters
        this.sortedInfo = sorter

        this.fetch({
          sortField: sorter.field,
          sortOrder: sorter.order,
          ...this.queryParams,
          ...filters
        })
      },
      fetch(params = {}) {
        this.loading = true
        if (this.paginationInfo) {
          // 如果分页信息不为空，则设置表格当前第几页，每页条数，并设置查询分页参数
          this.$refs.TableInfo.pagination.current = this.paginationInfo.current
          this.$refs.TableInfo.pagination.pageSize = this.paginationInfo.pageSize
          params.pageSize = this.paginationInfo.pageSize
          params.pageNum = this.paginationInfo.current
        } else {
          // 如果分页信息为空，则设置为默认值
          params.pageSize = this.pagination.defaultPageSize
          params.pageNum = this.pagination.defaultCurrent
        }
        this.$get('/admin/merParam/industryMapInfo', {
          ...params
        }).then((r) => {
          let data = r.data
          const pagination = {...this.pagination}
          pagination.total = data.total
          this.dataSource = data.rows
          this.pagination = pagination
          this.loading = false
        })
      },
    },
    watch: {
      'query.instId'(newValue, oldValue) {
        if (newValue !== oldValue) {
          this.listUrlParam= {'q': newValue}
        }
      }
    },
  }
</script>

<style lang="less" scoped>
  @import "../../../../../../static/less/Common";
</style>

